package com.xudongbase.common.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * jackson自定义日期时间序列化类
 *
 * @author xudongmaster
 */
@Component("jacksonCustomDateTimeSerializer")
public class CustomDateTimeSerializer extends JsonSerializer {
    /**
     * 日期时间格式
     */
    @Value("${json.dateTime.format}")
    private String format;

    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if(value instanceof LocalDateTime){
            jsonGenerator.writeString(((LocalDateTime) value).format(DateTimeFormatter.ofPattern(format)));
        }
    }
}
